<!--
 * @Description: 
 * @Date: 2024-07-17 10:22:44
 * @LastEditTime: 2024-07-19 14:10:06
-->
<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '预约',
  },
}
</route>
<template>
  <view
    class="bg-white bgImg overflow-hidden w-screen h-screen"
    :style="{ marginTop: safeAreaInsets?.top + 'px' }"
  >
    <view class="formCont">
      <wd-form ref="form" :model="queryParams" class="pt-40rpx pb-30rpx">
        <wd-cell-group style="border-bottom-right-radius: 36rpx; border-bottom-left-radius: 36rpx">
          <wd-picker
            :columns="columns"
            label="选择业务"
            placeholder="请选择业务类型"
            label-width="100px"
            prop="type"
            v-model="queryParams.type"
            :column-change="onChangeDistrict"
            :display-format="displayFormat"
            :rules="[{ required: true, message: '请选择业务类型' }]"
          />
          <wd-textarea
            label="补充说明"
            label-width="100px"
            prop="remark"
            v-model="queryParams.remark"
            placeholder="请进行补充说明"
          />
          <wd-calendar
            label="预约时间"
            label-width="100px"
            placeholder="请选择预约时间"
            :before-confirm="beforeConfirm"
            prop="appointTime"
            type="date"
            v-model="queryParams.appointTime"
            :rules="[{ required: true, message: '请选择预约时间' }]"
          />
          <wd-input
            label="姓名"
            label-width="100px"
            prop="name"
            v-model="queryParams.name"
            placeholder="请输入姓名"
            :rules="[{ required: true, message: '请填写姓名' }]"
          />
          <wd-input
            label="联系方式"
            label-width="100px"
            prop="contactMethod"
            v-model="queryParams.contactMethod"
            placeholder="请输入联系方式"
            :rules="[
              { required: true, message: '请填写联系方式' },
              {
                pattern:
                  /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
                message: '请输入正确的手机号码',
                trigger: 'blur',
              },
            ]"
          />
        </wd-cell-group>
      </wd-form>
    </view>
    <view class="footer fw-600" @click="handleSubmit">提交</view>
  </view>
</template>

<script lang="ts" setup>
import PLATFORM from '@/utils/platform'
import { useToast, useMessage } from 'wot-design-uni'
import * as getApi from '../../service/TouristReview/index'

const message = useMessage()
const toast = useToast()

defineOptions({
  name: 'Home',
})
const queryParams = reactive({
  type: '',
  remark: '',
  appointTime: null,
  name: '',
  contactMethod: '',
})

const form = ref()
const district = ref(null)
const columns = ref([])
// const params2 = reactive({
//   pageNo: 1,
//   pageSize: 100,
//   dictType: 'countryside_appointment_type',
// })
// // 获取预约大类数据
// async function getTypeDictData() {
//   const data: any = await getApi.getDictData({ ...params2 })
// }
const params = reactive({
  pageNo: 1,
  pageSize: 100,
  dictType: 'countryside_appointment_detail_type',
})
// 获取预约数据
async function getDictData() {
  const data: any = await getApi.getDictData({ ...params })
  const items = data.data.list.reverse().filter((item, index, self) => {
    return self.findIndex((t) => t.value === item.value) === index
  })
  district.value = processAndGroupByPrefix(items)
  columns.value = [district.value[0], district.value[district.value[0][0].value]]
}

// 处理大分类
function categorizeData(data) {
  // 创建一个映射来存储已经处理过的大类
  const categories = new Map()
  data.forEach((item) => {
    // 提取label中的大类
    const match = item.label.match(/【([^】]+)】/)
    if (match && match[1]) {
      // 获取大类名称
      const category = match[1]
      // 如果这个大类还没被添加到映射中，则添加它
      if (!categories.has(category)) {
        categories.set(category, categories.size + 1) // 分配一个唯一的value，映射大小+1
      }
    }
  })
  return Array.from(categories.entries()).map(([label, value]) => ({ label, value }))
}

// 处理小分类
function processAndGroupByPrefix(items) {
  categorizeData(items)
  const district = {
    '0': categorizeData(items),
  }
  const prefixMap = district[0].reduce((acc, curr) => {
    acc[curr.label] = curr.value.toString() // 将value转换为字符串
    return acc
  }, {}) // 初始值为一个空对象
  items.forEach((item) => {
    // 提取标签中的前缀
    const prefix = item.label.match(/【([^】]*)】/)?.[1] || ''
    // 查找对应的分组 key
    const key = prefixMap[prefix] || 'unknown'
    // 没有这个 key 的数组，则初始化一个空数组
    if (!district[key]) {
      district[key] = []
    }
    // 构建新的对象
    const newValue = parseInt(item.value, 10) // 将 value 转换为整数
    district[key].push({ label: item.label.replace(/【[^】]*】/, ''), value: newValue })
  })
  return district
}
const onChangeDistrict = (pickerView, value, columnIndex, resolve) => {
  const item = value[columnIndex]
  if (columnIndex === 0) {
    pickerView.setColumnData(1, district.value[item.value])
  }
  resolve()
}

const displayFormat = (items) => {
  return items
    .map((item) => {
      return item.label
    })
    .join('-')
}

const beforeConfirm = ({ value, resolve }) => {
  if (value < Date.now()) {
    toast.error('不能选择小于今天的日期，预约时间必须是未来的时间')
    resolve(false)
  } else {
    resolve(true)
  }
}
const handleSubmit = () => {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        try {
          message
            .confirm({
              title: '是否提交',
            })
            .then(() => {
              getApi
                .createReservation({
                  ...queryParams,
                  type: queryParams.type[0],
                  detailType: queryParams.type[1],
                })
                .then((res) => {
                  if (res.msg === '成功') {
                    toast.success('预约成功')
                    queryParams.type = ''
                    queryParams.remark = ''
                    queryParams.appointTime = null
                    queryParams.name = ''
                    queryParams.contactMethod = ''
                  } else {
                    toast.warning(res.msg)
                  }
                })
            })
            .catch(() => {
              toast.info('取消提交')
            })
        } catch (error) {
          console.log(error)
        }
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 测试 uni API 自动引入
onLoad(() => {
  // getTypeDictData()
  getDictData()
})
</script>

<style>
.bgImg {
  background: url('../../static//images//bgImg.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.formCont {
  margin: 45% 20rpx 20rpx 20rpx;
  background: #fff;
  border-radius: 20rpx;
}
.footer {
  bottom: 10rpx;
  height: 90rpx;
  margin: 20rpx;
  font-size: 32rpx;
  line-height: 90rpx;
  text-align: center;
  background-color: #fff;
  border-radius: 18rpx;
}
::v-deep.wd-textarea__value {
  padding-right: 0 !important;
  margin-top: 6rpx !important;
  background: rgba(240, 240, 240) !important;
}
::v-deep.wd-input.is-cell,
::v-deep.wd-picker__cell,
::v-deep.wd-textarea.is-cell,
::v-deep.wd-calendar__cell {
  display: block !important;
  padding-top: 0rpx !important;
  padding-bottom: 40rpx !important;
}
::v-deep.wd-input__body,
::v-deep.wd-calendar__body,
::v-deep.wd-picker__body {
  height: 80rpx !important;
  line-height: 80rpx !important;
  background: rgba(240, 240, 240) !important;
}
::v-deep.wd-input.is-cell .wd-input__inner {
  height: 80rpx !important;
  line-height: 80rpx !important;
}
::v-deep.wd-picker__arrow,
::v-deep.wd-calendar__arrow {
  line-height: 80rpx !important;
}
::v-deep.uni-textarea-textarea,
::v-deep.uni-textarea-placeholder {
  line-height: 40rpx !important;
}
::v-deep.uni-textarea-placeholder .uni-textarea-placeholder {
  line-height: 80rpx !important;
}
::v-deep.wd-picker__label,
::v-deep.wd-textarea__label-inner,
::v-deep.wd-calendar__label,
::v-deep.wd-input__label-inner {
  width: 100% !important;
  max-width: 100% !important;
  font-size: 30rpx !important;
}
</style>
